package com.crc.luojian.util;

import com.crc.luojian.annotation.Autowired;
import com.crc.luojian.annotation.Component;
import com.crc.luojian.component.TransactionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Objects;

/**
 * @program: luojian-springframework
 * @description:
 * @author: luojian58
 * @create: 2021-06-14 10:27
 */

public final class ConnectionUtils {
    //存储当前线程的数据库连接
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal();

    public static Connection getCurrentThread(){
        Connection connection = threadLocal.get();
        if(Objects.isNull(connection)){
            connection = DBUtil.getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }
    public static void setConnection(Connection connection){
        threadLocal.set(connection);
    }
    public static void executeUpdate(String sql) throws SQLException {
        Connection connection = getCurrentThread();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.execute();
    }

    public static void releaseConnection() {
        Connection connection = getCurrentThread();
        try {
            connection.close();
            threadLocal.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
